import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Button, Table, Pagination, Modal, message, Input,Icon, List ,Avatar } from 'antd';
import {routerRedux} from 'dva/router';
import styles from './index.less';

const confirm = Modal.confirm;
const Search = Input.Search;

@connect(({ customApi, loading }) => ({
  customApi,
  loading: loading.effects['customApi/fetch'],
}))

class CustomApi extends Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      limit: 10,
      currentApiId: null,
      apiNames: null,
      tableLoading: true
    };
    this.columns = [
      {
        key: 'name',
        align: 'left',
        title: 'API列表',
        dataIndex: 'name',
      },
      {
        title: '操作',
        align: 'left',
        render: (text, row) => {
          return <div>
            <Button htmlType='button' size='small' className={styles.processBtn} onClick={() => this.editApi(row)}>
              <FormattedMessage
                id="app.processTemplate.btn-edit"
              />
            </Button>
            <Button type="danger" htmlType='button' size='small' className={styles.processBtn} onClick={() => this.delApi(row)}>
              <FormattedMessage
                id="app.processTemplate.btn-del"
              />
            </Button>
          </div>;
        },
        width: '200px',
      },
    ];

  }


  componentDidMount() {
    this.fetchApiListById()
  }

  fetchApiListById=()=>{
    const that = this;
    const newPage = that.state.page;
    const newLimit = that.state.limit;
    const newApiNames = that.state.apiNames;
    const { dispatch, currentUser } = this.props;
    // TODO 这个地方currentUser可能会为空，需要加以判断
    console.log(currentUser);
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customApi/fetch',
        payload: { robotId: currentUser.robotId, page: newPage, limit: newLimit,apiNames: newApiNames },
        callback:(res)=>{
          this.setState({
            tableLoading: false
          })
        }
      });
    });
  };

  delApiById(id){
    const that = this;
    const { dispatch } = that.props;
    that.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customApi/delete',
        payload: {apiId: id },
        callback: (res)=>{
          if(res.msg){
            message.info(res.msg);
            that.fetchApiListById()
          }
        }
      });
    });
  }

  editApi(row) {
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customApi/redirect',
        payload: {apiId:row._id},
      });
    });
  }

  delApi(row) {
    const  that = this;
    confirm({
      title: '删除任务',
      content: '确认删除该API接口吗？',
      okText: '确认',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        that.delApiById(row._id)
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  setApiName(val){
    this.setState({
      apiNames:val,
      tableLoading: true
    },()=>{
      this.fetchApiListById()
    });
  }

  addApi(){
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customApi/redirect',
        payload: { },
      });
    });
  }

  // 翻页
  fanye(e) {
    this.setState({
      page: e,
      tableLoading: true
    }, () => {
      this.fetchApiListById();
    });
  }

  render() {
    const { customApi, loading } = this.props;
    const {
      items,
      total,
    } = customApi;
    return (
      <Suspense fallback={<PageLoading/>}>
        <PageHeaderWrapper>
          <Row className={styles.colorBackground}>
            <Col style={{ padding: 10 }} xs={24}>
              <div className={styles.title}>
                <FormattedMessage
                  id="app.customApi.title"
                />
              </div>
            </Col>
          </Row>
          <Card
            bordered={false}
          >
            <div>
              <Button type="primary" icon="plus" htmlType="button" onClick={()=>this.addApi()}>
                <FormattedMessage id="app.customApi.add" />
              </Button>
              <Search
                placeholder="输入API名称"
                onSearch={value => this.setApiName(value)}
                style={{ width: 200,float:'right' }}
              />
            </div>
            <Table
              rowKey="_id"
              dataSource={items}
              columns={this.columns}
              style={{ marginTop: '10px' }}
              pagination={false}
              algin="center"
              loading={this.state.tableLoading}
            />
            <Pagination
              total={total}
              onChange={e => this.fanye(e)}
              style={{ float: 'right', marginTop: '10px' }}
            />
          </Card>
        </PageHeaderWrapper>
      </Suspense>
    );
  }
}

export default connect (({ user }) => ({
  currentUser: user.currentUser
}))(CustomApi);
